/**
 * 超简陋app发布工具
 * 发布流程：gradle编译->解析apk->解析Git->发送apk和manifest
 * @author yangbin@gzhaoku.com
 */

var request = require('request');
var fs = require('fs');
var exec = require('child_process').exec;


var req = request.defaults({jar: true});

//环境变量，不同的APP请修改这里
var apkName = 'pos_',
    manifestName = './manifest.json';

//程序变量
var mode = process.argv[2],
    baseUrl,
    serverPath,
    apkPath,
    buildCmd = 'gradle build',
    note,
    build,
    version;

if(mode == 'dev'){
    baseUrl = 'http://dstatic.test.gzhaoku.com/mall-pages/pos/apk/';
    serverPath = 'root@game.uwan99.com:/data/mall-pages/pos/apk/';
    apkPath = './app/build/outputs/apk/debug/app-debug.apk';
    console.log('Deploy dev...');

}else if(mode == 'prod'){
  baseUrl = 'https://dstatic.gzhaoku.com/mall-pages/pos/apk/';
  serverPath = 'root@nginx.hk:/data/www/dstatic.gzhaoku.com/mall-pages/pos/apk/';
  apkPath = './app/release/app-release.apk';
  console.log('Deploy prod...');
}


//1. 编译打包

var buildApk = function(cb){
    console.log('Building apk...');
    exec(buildCmd, (error, stdout, stderr) => {
        if(error){
            console.error(`exec error: ${error}`);
            return;
        }

        cb();

    });
}

//2. 解析apk

//解析Git日志，用来备注apk
var readGitLog = function(cb){
    console.log('Read git log of HEAD...');
    exec('git log --oneline -1 --pretty=format:"%ad[%cn] %s" --date=short .| cat', (error, stdout, stderr) => {
        if(error){
            console.error(`exec error: ${error}`);
            return;
        }

        note = stdout;

        console.log('note = '+note);

        cb();

    });
}

//解析Apk文件，将versionCode和versionName从里面解析出来
var extractApk = function(cb){
    console.log('Extract apk...');
    exec('aapt dump badging '+apkPath, (error, stdout, stderr) => {
        if(error){
            console.error(`exec error: ${error}`);
            return;
        }


        var versionCode = /versionCode='(\d+)'/g;
        var versionName = /versionName='([\.0-9]+)'/g;

        var m1 = versionCode.exec(stdout);
        if(m1.length > 0){
            build = m1[1];
        }else{
            console.log(`${stdout}`);
        }

        var m2 = versionName.exec(stdout);
         if(m2.length > 0){
             version = m2[1];
         }

         console.log('build = '+build);
         console.log('version = '+version);

         cb();
    })

}


//复制apk到测试环境
var sendToServer = function(cb){

    var apkFileName = apkName + version+'.apk';

    exec('scp ' + apkPath + ' '+ serverPath + apkFileName, (error, stdout, stderr) => {
        if(error){
            console.error(`exec error: ${error}`);
            return;
        }


        var manifest = {
            build: build,
            version: version,
            url: baseUrl + apkFileName,
            apkFile: apkFileName,
            note: note
        };

        fs.writeFileSync(manifestName, JSON.stringify(manifest));

        exec('scp ' + manifestName + ' ' + serverPath, (error, stdout, stderr) => {
            if(error){
                console.error(`exec error: ${error}`);
                return;
            }

            cb();

        });



    });
}


//开始执行
buildApk(function(){//编译apk

    readGitLog(function(){//读取git日志

        extractApk(function(){//读取版本号

            sendToServer(function(r){//传送文件到服务器

            }, function(err){
                console.log(err);
            });

        });
    });
});

if(mode == 'dev'){
    //开始执行
    buildApk(function(){//编译apk

        readGitLog(function(){//读取git日志

            extractApk(function(){//读取版本号

                sendToServer(function(r){//传送文件到服务器

                }, function(err){
                    console.log(err);
                });

            });
        });
    });


}else if(mode == 'prod'){

    readGitLog(function(){//读取git日志

      extractApk(function(){//读取版本号

          sendToServer(function(r){//传送文件到服务器

          }, function(err){
              console.log(err);
          });

      });
  });

}